package com.common.app.utls

import android.os.Build
import android.text.TextUtils
import androidx.annotation.RequiresApi
import com.common.base.security.Base64Utils
import java.nio.charset.StandardCharsets
import java.security.InvalidKeyException
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
import java.util.Base64
import java.util.Locale
import javax.crypto.Mac
import javax.crypto.spec.SecretKeySpec


/**
 *
 * 作者：sosou
 *
 * 版本：1.0
 *
 * 创建日期：17/6/2025
 *
 * 描述：
 *
 * 修订历史：
 *
 */
object MD5Utils {

    fun md5(source: String, toUpperCase: Boolean): String {
        val sb = StringBuilder(32)
        try {
            val md = MessageDigest.getInstance("MD5")
            val array = md.digest(source.toByteArray(StandardCharsets.UTF_8))
            for (b in array) {
                if (toUpperCase) {
                    sb.append(
                        Integer.toHexString(b.toInt() and 0xFF or 0x100)
                            .uppercase(Locale.getDefault()).substring(1, 3)
                    )
                } else {
                    sb.append(Integer.toHexString(b.toInt() and 0xFF or 0x100).substring(1, 3))
                }
            }
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
        return sb.toString()
    }


    fun generateSHA256Sign(signKey: String, content: String): String? {
        return if (TextUtils.isEmpty(signKey)) content else try {
            val digest = MessageDigest.getInstance("SHA-256")
            digest.update(signKey.toByteArray())
            digest.update(content.toByteArray())
            val hashBytes = digest.digest()
            val hexString = StringBuilder()
            for (hashByte in hashBytes) {
                val hex = Integer.toHexString(0xff and hashByte.toInt())
                if (hex.length == 1) hexString.append('0')
                hexString.append(hex)
            }
            hexString.toString()
        } catch (e: NoSuchAlgorithmException) {
            throw RuntimeException(e) // 应该永远不会发生
        }
    }

    // 使用HMAC-SHA256生成签名
    fun generateHmacSha256Signature(data: String, key: String): String {
        val algorithm = "HmacSHA256"
        val secretKey = SecretKeySpec(key.toByteArray(), algorithm)
        val mac = Mac.getInstance(algorithm)
        mac.init(secretKey)
        val hmacData = mac.doFinal(data.toByteArray())
//        return Base64.getEncoder().encodeToString(hmacData)
        return Base64Utils.encode(hmacData)

    }
}